<template>
  <div class="dialogForm">
    <el-dialog title="审批流程" :visible.sync="showDialogForm" :width="dialogWidth" :close-on-click-modal="false" :destroy-on-close="true" :show-close="false">
      <el-form ref="form" :model="form" :rules="dialogFormRule" label-width="100px">
        <el-form-item label="审批步骤序号">
          <span>{{ form.stepNumber }}</span>
        </el-form-item>
        <el-form-item label="审批步骤名称">
            <el-input v-model="form.stepName"></el-input>
        </el-form-item>
        <el-form-item prop="approvalList" label="审批人">
          <el-tag v-for="item,index in form.approvalList" closable :key="index" @close="deleteUserEvent(item)" style="margin:2px;">{{ item.nickname }}</el-tag>
          <el-button type="text" size="mini" @click="addApprovalEvent">添加审批人</el-button>
          <!-- <el-col :span="20">
            <el-tag v-for="item,index in form.approvalList" closable :key="index" @close="deleteUserEvent(item)" style="margin:2px;">{{ item.nickname }}</el-tag>
          </el-col>
          <el-col :span="2">
            <el-button type="text" size="mini" @click="addApprovalEvent">添加审批人</el-button>
          </el-col> -->
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" size="mini" @click="cancelEvent">取 消</el-button>
        <el-button type="primary" size="mini" @click="confirmEvent">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户dialog -->
    <el-dialog title="选择用户" :visible.sync="userDialog.showUserDialog" :width="userDialogWidth" @close="dialogCloseEvent" @open="getUserList">
      <el-table :data="userDialog.tableData" width="100%" height="500px" v-loading="userDialog.loading" @select="userDialogTableHandlerSelect" @select-all="userDialogTableHandlerSelect" :destroy-on-close="false">
        <el-table-column type="selection" label="" align="center" width="60"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center" width="">
          <template slot-scope="{row,$index}" slot="header">
            <table-head-filter label="用户名" type="input" :bindData="userDialog.username"  filterField="username" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="姓名" align="center" width="">
          <template slot-scope="{row,$index}" slot="header">
            <table-head-filter label="姓名" type="input" :bindData="userDialog.nickname"  filterField="nickname" @change="filterChangeEvent"></table-head-filter>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="">
          <template slot-scope="{row,$index}">
            <span>{{ row.sex == 1 ? '女' : row.sex == 2 ? '男' : row.sex }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色" align="center" width=""></el-table-column>
        <el-table-column prop="departmentName" label="部门" align="center" width=""></el-table-column>
        <el-table-column prop="mobile" label="手机号" align="center" width=""></el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="userDialog.currentPage" :page-sizes="[10,20,40,80,100]" :page-size="userDialog.pageSize" background :layout="paginationLayout" :small="paginationIsUseSmall" :total="userDialog.total" style="margin-top:10px;"></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" size="mini" @click="userDialogCancelEvent">取 消</el-button>
        <el-button type="primary" size="mini" @click="userDialogConfirmEvent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { reqApprovalUserList } from "@/api/purchaseInventoryApproveProcess.js";
import TableHeadFilter from "@/components/tableHeadFilter/index.vue";
import { cloneDeep } from "lodash";
export default {
  components:{
    TableHeadFilter
  },
  props: {
    processItem:{
      type:Object,
      require:false,
      default:()=>({})
    },
    stepNumber:{
      type:Number,
      require:false,
      default:1
    },
    processFormState:{
      type:Number,
      require:false,
      default:0  //0-新增 1-编辑
    }
  },
  data() {
     const validateApprovalList = (rule, value, callback) => {
        if (value.length === 0) {
          callback(new Error('请至少选择一个审批人'));
        } else {
          callback();
        }
     };
    return {
      showDialogForm:true,
      form: {
        randomId:"",
        stepNumber:"",
        stepName:"",
        approvalList:[],
        selectedTmpUserList:[],
        remark:""
      },
      dialogFormRule:{
        approvalList: [{require:true,validator:validateApprovalList,trigger: 'change'}]
      },
      userDialog:{
        showUserDialog:false,
        tableData:[],
        currentPage:1,
        pageSize:20,
        total:0,
        loading:false,
        username:"",
        nickname:""
      },
      clientWidth:1920  //设备屏幕宽度
    }
  },
  mounted(){
    this.getCurrentDeviceWidth();
    window.addEventListener("resize",this.getCurrentDeviceWidth);
  },
  beforeDestroy(){
    window.removeEventListener("resize",this.getCurrentDeviceWidth);
  },
  computed: {
    showForm() {
      const isShow = this.isShow
      return isShow
    },
    dialogWidth(){
      const domWidth = this.clientWidth;
      if(domWidth >= 300 && domWidth <= 600){
        return "98%";
      }
      if(domWidth > 600){
        return "30%";
      }
    },
    paginationLayout(){
      const domWidth = this.clientWidth;
      if(domWidth >= 300 && domWidth <= 600){
        return "prev, pager, next,total";
      }
      if(domWidth > 600){
        return "prev, pager, next,total, sizes, jumper";
      }
    },
    paginationIsUseSmall(){
      const domWidth = this.clientWidth;
      if(domWidth >= 300 && domWidth <= 600){
        return true;
      }
      if(domWidth > 600){
        return false;
      }
    },
    userDialogWidth(){
      const domWidth = this.clientWidth;
      if(domWidth >= 300 && domWidth <= 600){
        return "98%";
      }
      if(domWidth > 600){
        return "60%";
      }
    }
  },
  watch:{
    processItem:{
      handler(newVal,oldVal){
        if(newVal && this.processFormState === 1){
          const { stepNumber,stepName,approvalList,remark,randomId } = newVal;
          this.form.randomId = randomId;
          this.form.stepNumber = stepNumber;
          this.form.stepName = stepName;
          this.form.approvalList = approvalList;
          this.form.remark = remark;
        }
      },
      immediate:true
    },
    stepNumber:{
      handler(newVal,oldVal){
        console.log(newVal,'stepNumber');
        if(newVal > 0 && this.processFormState === 0){
          this.form.stepNumber = newVal;
          this.form.randomId = this.generateRandomId();
        }
      },
      immediate:true
    }
  },
  methods: {
    addApprovalEvent(){
      this.userDialog.showUserDialog = true;
    },
    getUserList(){
      const { currentPage, pageSize,username,nickname } = this.userDialog;
      const params = {
        current:currentPage,
        size:pageSize,
        username:username,
        nickname:nickname
      }
      this.userDialog.loading = true;
      reqApprovalUserList(params).then(response => {
        if(response.data.code == 200){
          const list = response.data.data.content;
          this.userDialog.tableData = list;
          this.userDialog.total = response.data.data.totalElements;
        }
        this.userDialog.loading = false;
        console.log("分页获取用户列表信息",response);
      }, error => {
        this.userDialog.loading = false;
        console.log("分页获取用户列表信息",error);
      })
    },
    handleCurrentChange(val){
      this.userDialog.currentPage = val;
      this.getUserList();
    },
    handleSizeChange(val){
      this.userDialog.pageSize = val;
      this.getUserList();
    },
    cancelEvent(){
      this.$emit('formChange',null);
      this.clearFormData();
    },
    confirmEvent(){
      this.$refs.form.validate(validate => {
        if(validate){
          this.$emit('formChange',cloneDeep(this.form));
          this.clearFormData();
        }
      })
    },
    clearFormData(){
      this.form.stepNumber = "";
      this.form.stepName = "";
      this.form.approvalList = [];
      this.form.remark = "";
      this.form.randomId = this.generateRandomId();
    },
    generateRandomId(){
      const timestamp = new Date().getTime();
      const randomNum = parseInt(Math.random() * 1000) + 1000;
      const randomId = timestamp + "" + randomNum;
      console.log('生成随机id:',randomId);
      return randomId;
    },
    deleteUserEvent(userInfo){
      const userId = userInfo.id;
      const index = this.form.approvalList.findIndex(val => val.id == userId);
      this.form.approvalList.splice(index,1);
    },
    userDialogCancelEvent(){
      this.userDialog.showUserDialog = false;
    },
    userDialogTableHandlerSelect(selected,row){
      const selectedUserList = selected.map(val => {
        return {
          userId:val.id,
          nickname:val.nickname,
          username:val.username
        }
      });
      this.form.selectedTmpUserList = selectedUserList;
    },
    userDialogConfirmEvent(){
      if(this.form.selectedTmpUserList.length === 0){
        Dialog.alert({title:'提示',message:'未选择任何用户'}).then(confirm => {});
        return;
      }
      for(let j = 0; j < this.form.selectedTmpUserList.length; j ++){
        const t = this.form.selectedTmpUserList[j];
        if(this.form.approvalList.findIndex(val => val.userId === t.userId) === -1){
          this.form.approvalList.push(t);
        }
      }
      this.userDialog.showUserDialog = false;
    },
    dialogCloseEvent(){
      this.form.selectedTmpUserList = [];
      this.userDialog.tableData = [];
    },
    //tableHeadFiler的change事件
    filterChangeEvent(parameter){
      const { state, filterField, selectedValue } = parameter;
      if(state === 'clear'){
        //清空操作
        if(this.userDialog[filterField] !== ""){
          this.userDialog[filterField] = "";
          this.getUserList();
        }
      }
      if(state === 'confirm'){
        //确定操作
        this.userDialog[filterField] = selectedValue;
        if(selectedValue !== ""){
          this.getUserList();
        }
      }
    },
    getCurrentDeviceWidth(){
      const domWidth = document.documentElement.clientWidth;
      this.clientWidth = domWidth;
      console.log("当前屏幕宽度:",domWidth);
    }
  }
}
</script>